package cn.itcast.bos.web.action.take_delivery;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototyoe")
public class PromotionAction extends BaseAction<Promotion> {

    //图片管理image_manage
    @Action(value = "image_manage", results = { @Result(name = "success" ,type = "json") })
    public String imgMgt(){
        //存储文件的绝对路径
        String rootPath = ServletActionContext.getServletContext().getRealPath("/upload/");
        //相对路径
        String rootUrl = ServletActionContext.getRequest().getContextPath()+"/upload/";

        //遍历目录取得的文件信息
        List<Map<String, Object>> fileList = new ArrayList<>();
        //当前的上传目录
        File directory = new File(rootPath);

        //图片扩展名
        String[] fileTypes = new String[]{"gif","jpg","jpeg","png","bmp"};

        if (directory.listFiles() != null) {
            for (File file : directory.listFiles()) {
                Map<String, Object> hash = new HashMap<>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else {
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", true);
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                fileList.add(hash);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("moveup_dir_path", "");
        result.put("current_dir_path", rootPath);
        result.put("current_url", rootUrl);
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);
        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS;
    }

    @Autowired
    private PromotionService promotionService;

    private File titleImgFile;   //获取文件
    private String titleImgFileFileName; //获取名字
    private String titleImgFileContentType;  //获取文件类型

    public void setTitleImgFile(File titleImgFile) {
        this.titleImgFile = titleImgFile;
    }
    public void setTitleImgFileFileName(String titleImgFileFileName) {
        this.titleImgFileFileName = titleImgFileFileName;
    }
    public void setTitleImgFileContentType(String titleImgFileContentType) {
        this.titleImgFileContentType = titleImgFileContentType;
    }

    //保存宣传活动方法promotion_save.action
    @Action(value = "promotion_save", results = { @Result(name = "success" ,type = "redirect",
            location = "./pages/take_delivery/promotion.html") })
    public String save() throws IOException {
        //宣传图上图，保存至数据表，宣传图路径
        String savePath = ServletActionContext.getServletContext().getRealPath("/upload/");
        String saveUrl = ServletActionContext.getRequest().getContextPath()+"/upload/";

        //生成图片名称，截取文件后缀 并拼接成新的图片名称
        UUID uuid = UUID.randomUUID();
        String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
        String fileName =uuid+ext;

        //使用工具类完成临时文件复制到指定区域存储
        FileUtils.copyFile(titleImgFile,new File(savePath+"/"+fileName));
        model.setTitleImg(saveUrl+fileName);
        promotionService.save(model);
        return SUCCESS;
    }

    //分页查询promotion_pageQuery
    @Action(value = "promotion_pageQuery", results = { @Result(name = "success", type = "json") })
    public String query(){
        PageRequest request = new PageRequest(page - 1, rows);
        Page<Promotion> pageData = promotionService.findByPage(request);
        pushPageDataToValueStrack(pageData);

        return SUCCESS;
    }



}
